package org.ccay.core.ioc.impl;

import java.util.Map;

import javax.inject.Named;

import org.ccay.core.exception.ApplicationException;
import org.ccay.core.ioc.Ccay;
import org.ccay.core.ioc.ISelfInject;
import org.ccay.core.log.CcayLoggerFactory;
import org.ccay.core.log.ILogger;
import org.ccay.core.server.IAfterStartupHandler;
import org.ccay.core.server.StartupEventArgs;
import org.springframework.beans.BeansException;

/**
 * 自注入处理器
 * 
 * 2013/4/9 改为由IAfterStartupHandler触发，解决@Cache相关的Annotation不能被拦截的问题
 * 
 * @since 2012-1-19
 */
@Named
public class SelfInjectProcessor implements IAfterStartupHandler {	
	private ILogger logger = CcayLoggerFactory.getLogger(SelfInjectProcessor.class); 

	/* (non-Javadoc)
	 * @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization(java.lang.Object, java.lang.String)
	 */
	public Object postProcessBeforeInitialization(Object bean, String beanName)
			throws BeansException {
		return bean;
	}

	/* (non-Javadoc)
	 * @see org.ccay.core.server.IAfterStartupHandler#execute(java.lang.Object, org.ccay.core.server.StartupEventArgs)
	 */
	public void execute(Object sender, StartupEventArgs args) throws ApplicationException {
		Map<String, ISelfInject> injects = Ccay.getContext().getBeansOfType(ISelfInject.class);
		
		for(Map.Entry<String, ISelfInject> bean : injects.entrySet()){
			logger.debug("Before self-inject:" + bean.getKey());
			ISelfInject value = bean.getValue();
			value.setSelf(value);
		}		
	}

	public int getOrder() {
		return 0;
	}
}
